<!--
 * @Author: 熊志伟 xiongzhiwei
 * @Date: 2024-11-12 14:23:42
 * @LastEditors: huang liang miao 1127255342@qq.com
 * @LastEditTime: 2025-01-08 09:28:26
 * @FilePath: \sr_system_manager_ui\src\views\login\components\login.vue
 * @Description: 登录页
-->
<template>
  <el-form ref="loginRef" :model="loginForm" :rules="loginRules" class="login-form">
    <div class="title">
      <el-image :src="appNameImg" />
    </div>
    <el-form-item prop="username" style="margin-bottom: 24px;">
      <el-input v-model="loginForm.username" type="text" size="large" auto-complete="off" clearable
        placeholder="请输入工号/手机号">
      </el-input>
    </el-form-item>
    <!-- <el-form-item prop="code">
      <el-input v-model="loginForm.code" size="large" auto-complete="off" placeholder="验证码" style="width: 63%">
        <template #prefix><svg-icon icon-class="validCode" class="el-input__icon input-icon" /></template>
      </el-input>
      <div class="login-code">
        <img :src="codeUrl" @click="getCode" class="login-code-img" />
      </div>
    </el-form-item> -->
    <el-form-item prop="password" style="margin-bottom: 16px;">
      <el-input v-model="loginForm.password" type="password" size="large" auto-complete="new-password" placeholder="请输入密码" :readonly="isReadonly"
        show-password clearable @focus="isReadonly = false">
      </el-input>
    </el-form-item>
    <div class="remember">
      <el-checkbox v-model="loginForm.rememberMe">记住密码</el-checkbox>
      <!-- <el-button type="info" link :underline="false" @click="emits('forget')">忘记密码？</el-button> -->
    </div>
    <el-form-item style="width: 100%; margin-bottom: 16px;">
      <el-button :loading="loading" size="large" type="primary" style="width: 100%" @click.prevent="handleLogin">
        登录
      </el-button>
    </el-form-item>
    <div class="pb-[10px] leading-[12px] text-[12px] text-[#4E5969]">登录即代表同意 <el-link href="/agreement" type="primary" :underline="false"
        style="font-size: 12px;">用户协议</el-link>、<el-link href="/privacy" type="primary" :underline="false"
        style="font-size: 12px;">隐私协议</el-link></div>
  </el-form>
  
  <!-- 选择身份 -->
  <IdentityModal v-if="identityVisible" :visible="identityVisible" :identityCodeList="identityCodeList" @change="handleOk" />
</template>

<script setup lang="ts">
import { login, getPubKey, getIdentityCodeReq } from "@/api/login"
import Cookies from "js-cookie"
import { encrypt } from "@/utils/jsencrypt"
import useUserStore from "@/store/modules/user"
import { ElMessage } from "element-plus"
import { IDENTITYMAP, identityAvatar } from "@/utils/constText"
import appNameImg from '@/assets/images/app-name.png'

const emits = defineEmits(['forget'])

const userStore = useUserStore()
const route = useRoute()
const router = useRouter()
const { proxy } = getCurrentInstance()

const loginForm = ref({
  username: "",
  password: "",
  rememberMe: false,
  code: "",
  uuid: "",
});

const isReadonly = ref(true) // 解决chrome自动填充密码

const loginRules = {
  username: [{ required: true, trigger: "blur", message: "请输入您的账号" }],
  password: [{ required: true, trigger: "blur", message: "请输入您的密码" }],
  // code: [{ required: true, trigger: "change", message: "请输入验证码" }],
};

// const codeUrl = ref("");
// 验证码开关
// const captchaEnabled = ref(true);
// 注册开关
// const register = ref(false);
const redirect = ref(undefined)

const identityCodeList = ref([]) // 身份集合
const identityVisible = ref(false) // 选择身份弹窗
const curLoginParams = ref(null) // 当前登录名和密码

watch(
  route,
  (newRoute) => {
    redirect.value = newRoute.query && newRoute.query.redirect;
  },
  { immediate: true }
);

// 获取公钥
const { runAsync: getPubKeyReq } = useRequest(getPubKey, {
  manual: true,
})

// 获取身份列表
const { runAsync: getIdentityCode } = useRequest(getIdentityCodeReq, {
  manual: true,
})

const { run: loginFn, loading } = useRequest(login, {
  manual: true,
  onSuccess: (res) => {
    userStore.login(res);
    const query = route.query;
    const otherQueryParams = Object.keys(query).reduce((acc, cur) => {
      if (cur !== "redirect") {
        acc[cur] = query[cur];
      }
      return acc;
    }, {});
    router.push({ path: redirect.value || "/", query: otherQueryParams });
  },
  onError: () => {
    // 重新获取验证码
    // if (captchaEnabled.value) {
    //   getCode();
    // }
  },
});

// 校验账号密码
const { run: validUser } = useRequest(login, {
  manual: true,
  onSuccess: async (res) => {
    const identityCode = await getIdentityCode({username: loginForm.value.username}, {Authorization: `Bearer ${res}`})
    if(identityCode?.length > 1) { //身份集合大于1时，展示选择身份弹窗
      identityCodeList.value = identityCode?.map((code) => ({
        value: code,
        label: IDENTITYMAP?.[code],
        avatar: identityAvatar[code]
      }))
      identityVisible.value = true
    }
    else if(identityCode?.length === 1) {
      curLoginParams.value?.append('identityCode', identityCode?.[0])
      loginFn(curLoginParams.value)
    }
    else
      ElMessage({ message: '当前帐号身份丢失', type: 'error' })
  }
})

// 选择身份
function handleOk(code) {
  if(!curLoginParams.value) {
    ElMessage({ message: '参数丢失', type: 'error' })
    return
  }
  curLoginParams.value?.set('identityCode', code)
  identityVisible.value = false
  loginFn(curLoginParams.value)
}

function handleLogin() {
  proxy.$refs.loginRef.validate(async (valid) => {
    if (valid) {
      const pubKey = await getPubKeyReq()
      // 勾选了需要记住密码设置在 cookie 中设置记住用户名和密码
      if (loginForm.value.rememberMe) {
        Cookies.set("username", loginForm.value.username, { expires: 30 });
        Cookies.set("password", loginForm.value.password, {
          expires: 30,
        });
        Cookies.set("rememberMe", loginForm.value.rememberMe, { expires: 30 });
      } else {
        // 否则移除
        Cookies.remove("username");
        Cookies.remove("password");
        Cookies.remove("rememberMe");
      }
      const data = new FormData()
      const password = encrypt(pubKey, loginForm.value.password)
      data.append('username', loginForm.value?.username)
      data.append('password', password)
      curLoginParams.value = data
      validUser(data);
    }
  });
}

// const { run: getCode } = useRequest(getCodeImg, {
//   manual: true,
//   onSuccess: (res) => {
//     captchaEnabled.value =
//       res.captchaEnabled === undefined ? true : res.captchaEnabled;
//     if (captchaEnabled.value) {
//       codeUrl.value = "data:image/gif;base64," + res.img;
//       loginForm.value.uuid = res.uuid;
//     }
//   },
// });

function getCookie() {
  const username = Cookies.get("username");
  const password = Cookies.get("password");
  const rememberMe = Cookies.get("rememberMe");
  loginForm.value = {
    username: username === undefined ? loginForm.value.username : username,
    password:
      password === undefined ? loginForm.value.password : password,
    rememberMe: rememberMe === undefined ? false : Boolean(rememberMe),
  };
}

// getCode();
getCookie();
</script>

<style lang="scss" scoped>
.title {
  margin: 0px auto 32px;
  width: 218px;
  height: 48px;
}

.login-form {
  border-radius: 16px;
  background: #ffffff;
  padding: 40px 32px;

  .el-input {
    height: 46px;
    width: 322px;
  }
}

.remember {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 32px;
}

</style>